package com.hopedove.tempdemo.viewmodel

import android.graphics.Bitmap
import android.text.TextUtils
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.bumptech.glide.RequestManager
import com.hadilq.liveevent.LiveEvent
import com.hopedove.net.kotlin.ErrorResult
import com.hopedove.net.kotlin.SuccessResult
import com.hopedove.tempdemo.net.NoticeBill
import com.hopedove.tempdemo.net.SoapApi
import com.hopedove.tempdemo.net.data.NeedleKnitArrangeBaseInfo
import com.hopedove.tempdemo.net.data.SampleNoticeRequest
import com.hopedove.tempdemo.net.data.SampleNoticeResponse
import com.hopedove.tempdemo.repository.Repository
import com.hopedove.tempdemo.utils.BitmapUtil
import com.hopedove.tempdemo.utils.KnitArrangeCell
import com.hopedove.tempdemo.utils.KnitArrangementHelper
import com.hopedove.tempdemo.utils.TableSize
import com.hopedove.viewmodel.BaseViewModel
import kotlinx.coroutines.launch

class SampleNoticeViewModel(private val api: SoapApi = SoapApi()) : BaseViewModel() {

    private val _resp = LiveEvent<SampleNoticeResponse>()
    val resp: LiveData<SampleNoticeResponse> = _resp
    private val _triangleArrangeBitmap = MutableLiveData<Bitmap>()
    val triangleArrangeBitmap: LiveData<Bitmap> = _triangleArrangeBitmap
    private val _noticeBill = MutableLiveData<NoticeBill>()
    val noticeBill: LiveData<NoticeBill> = _noticeBill
    private val _knitArrangeBitmap = MutableLiveData<Bitmap>()
    val knitArrangeBitmap: LiveData<Bitmap> = _knitArrangeBitmap
    private val _knitArrangeContent = MutableLiveData<String>()
    val knitArrangeContent: LiveData<String> = _knitArrangeContent

    fun load(glide: RequestManager) = viewModelScope.launch {
        _loading.value = true

        val data = Repository.getSelectedItem() ?: return@launch
        val request = data.let {
            SampleNoticeRequest(
                CLOTHGROUP = it.CLOTHGROUP ?: "",
                CONTACTNO = it.CONTACTNO ?: "",
                MHJGH = it.MHJGH ?: "",
                BH = it.BH ?: "",
                GYSX = it.GYSX ?: "",
                PATTERNNO = it.PATTERNNO ?: "",
            )
        }

        api.getSampleNoticePrint(request).let { result ->
            when (result) {
                is SuccessResult -> {
                    val resp = result.value
                    _resp.value = resp
                    setTriangle(resp, glide)
                    resp.rst_zzpl?.let { setKnitDesign(it) }
                }
                is ErrorResult -> {
                }
            }
        }

        getLabelBill()
    }.invokeOnCompletion { _loading.value = false }

    private fun getLabelBill() = viewModelScope.launch {
        val data = Repository.getSelectedItem() ?: return@launch
        api.getNoticeBillInfo(data.SCLOTHTKTNO ?: "").let { result ->
            when (result) {
                is SuccessResult -> {
                    if (result.value.isNotEmpty()) {
                        _noticeBill.value = result.value[0]
                    }
                }

                is ErrorResult -> {
                }
            }
        }
    }

    // 三角排列
    private fun setTriangle(resp: SampleNoticeResponse, glide: RequestManager) =
        viewModelScope.launch {
            resp.rst_sjpl?.let { info ->
                Repository.buildTriangleArrange(
                    viewModelScope,
                    glide,
                    info.YNUM!!,
                    info.XNUM!!,
                    resp.sjpl!!
                )?.let {
                    _triangleArrangeBitmap.value = it
                }
            }
        }


    // 织针排列
    private fun setKnitDesign(zzpl: NeedleKnitArrangeBaseInfo) {

        zzpl.tables?.let { tables ->
            val above = tables.above.info.let { TableSize(it.rows, it.columns) }
            val below = tables.below?.info?.let { TableSize(it.rows, it.columns) }
            val aboveLeftMargin = if (tables.above.info.hasLeftMargin) 40 else 0
            val belowLeftMargin = if (tables.below?.info?.hasLeftMargin == true) 40 else 0

            val helper = KnitArrangementHelper(
                above,
                below,
                aboveLeftMargin,
                belowLeftMargin,
                tables.hasDivider
            )

            val datas = mutableListOf<KnitArrangeCell>()
            datas.addAll(tables.above.data.map { KnitArrangeCell(it.y, it.x, it.`val`) })
            datas.addAll(tables.below?.data?.map {
                KnitArrangeCell(
                    it.y,
                    it.x,
                    it.`val`,
                    false
                )
            } ?: mutableListOf())

            _knitArrangeBitmap.value = helper.drawCells(datas)
        }

        zzpl.imgData?.let { imageData ->
            if (!TextUtils.isEmpty(imageData)) {
                _knitArrangeBitmap.value = BitmapUtil.fromBase64(imageData)
                zzpl.remark?.let {
                    _knitArrangeContent.value = it
                }
            }
        }

        zzpl.tspl?.let { content ->
            _knitArrangeContent.value = content.replace("\r", "")
        }
    }

}